package servlet;

import bean.Banji;
import service.BanjiService;
import service.BanjiServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;


@WebServlet(name = "BanjiAddServlet" ,urlPatterns = "/banjiAddServlet")
public class BanjiAddServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //设置中文乱码问题
        response.setContentType ("text/html;charset=utf-8");
        request.setCharacterEncoding ("utf-8");
        // 1.获取前台页面发过来的标志位和数据内容
        String flag = request.getParameter ("flag");
        String bName = request.getParameter ("bName");
        String bAge = request.getParameter ("bAge");
        String tName = request.getParameter ("tName");
        String kouHao = request.getParameter ("kouHao");
        String num = request.getParameter ("num");
        // 2.打包数据后通过Service层实现对应的功能
        BanjiService banjiService = new BanjiServiceImpl ();
        // 根据隐藏域的结果分别实现增加和修改的功能
        int res = 0;
        Banji banji = null;
        if (flag.equals ("add")) {
            banji = new Banji (bName,bAge,tName,kouHao,num);
            res = banjiService.BanjiAddService (banji);
            System.out.println ("新增的结果是" + res);
        } else {
            banji = new Banji (Integer.parseInt (flag),bName,bAge,tName,kouHao,num);
            res = banjiService.BanjiModifyService (banji);
            System.out.println ("修改结果是" + res);
        }
        // 3.通过输出流向前台页面展示处理结果，然后重新请求一次数据
        PrintWriter writer = response.getWriter ();
        // 获取模块名称
        String contextPath = this.getServletContext ().getContextPath ();
        // 拼接请求路径
        String hrefPath = contextPath + "/banjiQueryServlet";

        if (res != 0) {
            writer.print ("<script>alert('班级信息管理成功');location.href = '" + hrefPath + "';</script>");
        } else {
            writer.print ("<script>alert('班级信息管理失败');location.href = '" + hrefPath + "';</script>");
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost (request,response);
    }
}
